package cn.com.nes.common.wx;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 客户端连接工具类
 * Create by yishuai on 2022/6/7
 **/
public class HttpClientUtils {

    /**
     * GET请求
     * @param url
     * @return
     * @throws IOException
     */
    public static String get(String url) throws IOException {
        String result = "";
        // 创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建get方式请求对象
        HttpGet httpGet = new HttpGet(url);
        httpGet.addHeader("Content-type", "application/json");
        // 通过请求对象获取响应对象
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        // 释放链接
        response.close();
        return result;
    }

    /**
     * post请求
     * @param url
     * @param param
     * @return
     */
    public static String post(String url, Map<String, String> param) throws IOException {
        //响应的请求数据
        String result = "";
        //创建HttpClent对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        //装填参数
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if(null != param) {
            for(Map.Entry<String,String> entry : param.entrySet()) {
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }
        //设置参数到请求对象中
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
        //设置请求头
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String res = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject json = JSONObject.parseObject(res);
            json = json.getJSONObject("data");
            result = json.toJSONString();
        }
        // 释放链接
        response.close();
        return result;
    }

    public static String postJSON(String url, JSONObject param) throws IOException {
        //响应的请求数据
        String result = "";
        //创建HttpClent对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        if(null != param) {
            StringEntity stringEntity = new StringEntity(param.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
        }
        //设置请求头
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 执行请求操作，并拿到结果（同步阻塞）
        CloseableHttpResponse response = httpClient.execute(httpPost);

        // 获取结果实体
        // 判断网络连接状态码是否正常(0--200都数正常)
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String res = EntityUtils.toString(response.getEntity(), "UTF-8");
            JSONObject json = JSONObject.parseObject(res);
            System.out.printf(json.toJSONString());
        }
        // 释放链接
        response.close();
        return result;
    }

    public static CloseableHttpResponse postJSONForResponse(String url, JSONObject param) throws IOException {
        //创建HttpClent对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建Post方式请求对象
        HttpPost httpPost = new HttpPost(url);
        if(null != param) {
            StringEntity stringEntity = new StringEntity(param.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            //设置参数到请求对象中
            httpPost.setEntity(stringEntity);
        }
        //设置请求头
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        // 执行请求操作，并拿到结果（同步阻塞）
        return httpClient.execute(httpPost);
    }
}
